package com.juzhencms.apps.busi.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.juzhencms.apps.busi.service.AdminMenuService;
import com.juzhencms.apps.busi.service.DictionaryService;
import com.juzhencms.apps.busi.service.MenuService;
import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.util.StringUtil;
import com.juzhencms.apps.base.common.util.WebUtil;

import lombok.extern.slf4j.Slf4j;


@Controller
@RequestMapping("/menu")
@Slf4j
public class MenuController  extends BaseController{
	
	@Autowired
	private AdminMenuService adminMenuService;
	
	@Autowired
	private MenuService menuService;
	
	@Autowired
	private DictionaryService dictionaryService;
	
	
	@RequestMapping(value="/gridlistData",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String gridlistData(HttpServletRequest request){
		Map data=new HashMap();
		int site_id = 0;
		String name = "";
		if(request.getParameter("site_id")!=null && !request.getParameter("site_id").toString().trim().equals("")){
			site_id=new Integer(request.getParameter("site_id").toString());
		}else{
			Map defaultSite=this.getCommonService().getJdbcDao().queryRow("select id from "+DBTable.site+" where del_flag=0 order by position asc,create_time asc limit 0,1");
			if(defaultSite!=null)
				site_id=new Integer(defaultSite.get("id").toString());
		}
		List whereParamList=new ArrayList();
		String where=" where del_flag=0 and site_id= ? ";
		whereParamList.add(site_id);
		String sortField="position";
		String sortOrder="asc";
		//查询列表数据
		List dataList=this.getCommonService().getJdbcDao().querySql("select id,name,parent_id as parentId,module,position,publish,create_time from "+DBTable.menu+" "+where+" order by "+sortField+" "+sortOrder+",create_time asc", whereParamList.toArray());
		if(dataList!=null && dataList.size()>0){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			for(int i=0;i<dataList.size();i++){
				Map row=(Map)dataList.get(i);
				Date date = (Date)row.get("create_time");
				row.put("create_time",sdf.format(date));
			}
		}
		data.put("data", dataList.toArray());
		return WebUtil.resultString(data,request);
	}
	
	@RequestMapping(value="/detailData/{id}",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String detailData(@PathVariable("id") String id,HttpServletRequest request){
		Map data=new HashMap();
		Map record=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.menu+" where id=?",new Object[]{id});	
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = (Date) (record.get("create_time")==null?"":record.get("create_time"));
		record.put("create_time",sdf.format(date) );
		data.put("data", record);
		
		return WebUtil.resultString(data,request);
	}
	
	@RequestMapping(value="/save",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String save(HttpServletRequest request){
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		data.put("del_flag", 0);
		String id=null;
		if(data.get("id")!=null){
			id=data.get("id").toString();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		if(id==null || id.equals("")){
			if(data.get("create_time")==null || data.get("create_time").equals("")){
				data.put("create_time", sdf.format(date));
			}
			Map prevMenu=this.getCommonService().getJdbcDao().queryRow("select position from "+DBTable.menu+" where del_flag=0 and parent_id=? order by position desc limit 1",new Object[]{data.get("parent_id").toString()});	
			int position = 0;
			if(prevMenu!=null) {
				 position = Integer.parseInt(prevMenu.get("position").toString());
			}
			data.put("position", position+1);
			data.put("create_user", this.getLoginUserId());
			this.getCommonService().getJdbcDao().addObj(DBTable.menu, data);
		}else{
			data.put("update_time", sdf.format(date));
			data.put("update_user", this.getLoginUserId());
			this.getCommonService().getJdbcDao().updateObj(DBTable.menu, data, "id");
		}
		Map result=new HashMap();
		result.put("result", 1);
		result.put("msg", "保存成功");
		
		return WebUtil.resultString(result,request);
		
	}
	
	@RequestMapping(value="/delete",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String delete(HttpServletRequest request){
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		
		String id=null;
		if(data.get("id")!=null){
			id=data.get("id").toString();
		}
		if(id==null || id.equals("")){
		}else{	
	        String[] idArray = id.split(",");
	        String tmpVar="?";
	        if(idArray!=null && idArray.length>0){
	        	Matcher matcher = Pattern.compile("\\d+").matcher(id);
	        	tmpVar=matcher.replaceAll("?");
	        }
	        this.getCommonService().getJdbcDao().updateSql("update "+DBTable.menu+" set del_flag=1,update_time=NOW() where id in ("+tmpVar+")",idArray);
		}
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		return WebUtil.resultString(result,request);
	}
	@RequestMapping(value="/getParentTreeMenuList/{site_id}/{id}",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String getParentTreeMenuList(@PathVariable("site_id") String site_id,@PathVariable("id") String id,HttpServletRequest request){
		if(id==null || "".equals(id) || "undefined".equals(id)) {
			id="0";
		}
		List dataList=this.getEditParentMenuTree(new Integer(id), 0, new Integer(site_id));
		Map data=new HashMap();
		data.put("data", dataList);
		return WebUtil.resultString(data,request);
	}
	
	private List getEditParentMenuTree(int id,int pid,int siteid){
		//System.out.println(id);
		List dataList=this.getCommonService().getJdbcDao().querySql("select id,name from "+DBTable.menu+" where parent_id=? and site_id=? and del_flag = 0 order by position asc,id asc",new Object[]{pid,siteid});
		for(int i=0;i<dataList.size();i++){
			Map menu=(Map)dataList.get(i);
			if(menu.get("id").toString().equals(""+id)){
				menu.put("chkDisabled",true);
				//System.out.println(id);
			}else{
				List subList=this.getEditParentMenuTree(id, new Integer(menu.get("id").toString()),siteid);
				if(subList!=null && subList.size()>0)
					menu.put("children", subList);
			}
		}
		return dataList;
	}
	@RequestMapping(value="/getSiteMenuTreeList",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String getSiteMenuTreeList(HttpServletRequest request){
		
		List dataList=new ArrayList();
		//查询所有站点数据
		List siteList=this.getCommonService().getJdbcDao().querySql("select concat('s',id) as id,0 as pId,name,'' as module from "+DBTable.site+" where del_flag=0 order by position asc,id asc");
		dataList.addAll(siteList);
		
		//查询一级栏目节点
		List pMenuList=this.getCommonService().getJdbcDao().querySql("select id,concat('s',site_id) as pId,name,module from "+DBTable.menu+" where parent_id=0 and del_flag=0 order by position asc,id asc");
		dataList.addAll(pMenuList);
		
		List menuList=this.getCommonService().getJdbcDao().querySql("select id,parent_id as pId,name,module from "+DBTable.menu+" where parent_id>0 and del_flag=0 order by position asc,id asc");
		dataList.addAll(menuList);
		
		
		Map data=new HashMap();
		data.put("data", dataList.toArray());
		
		return WebUtil.resultString(data,request);
	}
	
	
	private Map getMenuTreeData(int site_id, int parent_id, String whereStr) {
		// TODO Auto-generated method stub
		List whereParamList=new ArrayList();
		String where=" where del_flag=0 and site_id= ? and parent_id=? ";
		whereParamList.add(site_id);
		whereParamList.add(parent_id);
		if(whereStr!=null && !whereStr.trim().equals("")){
			where+=" and "+whereStr;
		}
		where+=" order by position asc";
		
		List moduleVars=dictionaryService.getDictionaryItemList("moduleVars");
		
		List menuList = this.getCommonService().getJdbcDao().querySql("select id,name as text,module,publish,template,link_url from " + DBTable.menu
				+ where, whereParamList.toArray());
		if (menuList != null && menuList.size() > 0) {
			for (int i = 0; i < menuList.size(); i++) {
				Map row = (Map) menuList.get(i);
				
				String extAttrString="";
				List extAttrList=new ArrayList();
				
				if(row.get("module")!=null && !row.get("module").equals("")){
					extAttrList.add("功能:"+dictionaryService.getText(moduleVars,row.get("module").toString()));
					
				}
				if(row.get("template")!=null && !row.get("template").equals("")){
					extAttrList.add("模板:"+row.get("template"));
				}
				if(row.get("link_url")!=null && !row.get("link_url").equals("")){
					extAttrList.add("链接:"+row.get("link_url"));
				}
				
				if(row.get("publish")!=null && row.get("publish").toString().equals("0")){
					extAttrList.add("未发布");
				}
				
				for(int a=0;a<extAttrList.size();a++) {
					if(a<extAttrList.size()-1) {
						extAttrString+=extAttrList.get(a)+",";
					}else {
						extAttrString+=extAttrList.get(a);
					}
				}
				
				
				if(!extAttrString.equals("")){
					row.put("text", row.get("text").toString()+" ["+extAttrString+"]");
				}
				
				
				Map tmp = this.getMenuTreeData(site_id,new Integer(row.get("id").toString()),whereStr);
				if (tmp != null)
					row.put("nodes", tmp.get("nodes"));
			}
			Map data = new HashMap();
			data.put("nodes", menuList);
			return data;
		} else {
			return null;
		}
	}
	@RequestMapping(value="/updatePosition",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String updatePosition(HttpServletRequest request){
		if(request.getParameter("position")==null || request.getParameter("id")=="")
			return "";
		this.getCommonService().getJdbcDao().updateSql("update "+DBTable.menu+" set position=? where id=?",new Object[]{request.getParameter("position"),request.getParameter("id")});
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		return WebUtil.resultString(result,request);
	}
	
	
	@RequestMapping(value="/addTestData",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String addTestData(@RequestBody Map data,HttpServletRequest request){
		Map result=new HashMap();
		List menuList=(List)data.get("menuList");
		if(menuList!=null && menuList.size()>0) {
			for(int i=0;i<menuList.size();i++) {
				String id=menuList.get(i).toString();
				menuService.addTestData(id);
			}
			
			
			//log.info(org.apache.commons.lang3.StringUtils.join(menuList, ","));
			
			/*List menuDataList=this.getCommonService().getJdbcDao().querySql("select id,module,name,site_id from "+DBTable.menu+" where del_flag=0 and module in('news','links','article') and id in ("+org.apache.commons.lang3.StringUtils.join(menuList, ",")+")");
			
			if(menuDataList!=null) {
				for(int m=0;m<menuDataList.size();m++) {
					try {
						Thread.sleep(5L);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					Map menu=(Map)menuDataList.get(m);
					String moduleName=menu.get("module").toString();
					String menuName=menu.get("name").toString();
					String menuId=menu.get("id").toString();
					String siteId=menu.get("site_id").toString();
					
					if(moduleName.equals("news")) {
						for(int i=0;i<20;i++){
							Map saveData=new HashMap();
							saveData.put("name", menuName+"-测试资讯数据标题测试资讯数据标题测试资讯数据标题"+ (i+1));
							saveData.put("subname", menuName+"-测试资讯数据标题"+ (i+1)+"副标题");
							
							saveData.put("image", "default_img.jpg");
							saveData.put("author", "匿名");
							saveData.put("source", "互联网");
							saveData.put("hits", 0);
							saveData.put("digs", 0);
							saveData.put("menu_id",menuId);
							saveData.put("site_id",siteId);
							
							saveData.put("description", menuName+"-测试资讯数据简介测试资讯数据简介测试资讯数据简介测试资讯数据简介测试资讯数据简介测试资讯数据简介测试资讯数据简介测试资讯数据简介测试资讯数据简介");
							saveData.put("content", "<p>"+menuName+"-测试资讯数据正文<br/>测试资讯数据正文<br/>测试资讯数据正文<br/>测试资讯数据正文<br/>测试资讯数据正文<br/></p>");
							saveData.put("create_time",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) );
							saveData.put("position", new Date().getTime());
							this.getCommonService().getJdbcDao().addObj(DBTable.news, saveData);
						}
					}else if(moduleName.equals("links")) {
						for(int i=0;i<20;i++){
							Map saveData=new HashMap();
							saveData.put("name", menuName+"-测试链接数据标题测试资讯数据标题"+ (i+1));
							saveData.put("image", "default_img.jpg");
							saveData.put("link_url", "http://www.baidu.com");
							saveData.put("menu_id",menuId);
							//saveData.put("site_id",siteId);
							saveData.put("create_time",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) );
							this.getCommonService().getJdbcDao().addObj(DBTable.links, saveData);
						}
					}else if(moduleName.equals("article")) {
						Map articleData=this.getCommonService().getJdbcDao().queryRow("select id from "+DBTable.article+" where menu_id=? and del_flag=0", new Object[] {menuId});
						if(articleData==null) {
							articleData=new HashMap();
							articleData.put("image", "default_img.jpg");
							articleData.put("menu_id",menuId);
							articleData.put("site_id",siteId);
							articleData.put("description", menuName+"-测试文章数据简介测试文章数据简介测试文章数据简介测试文章数据简介测试文章数据简介测试文章数据简介测试文章数据简介测试文章数据简介测试文章数据简介");
							articleData.put("content", "<p>"+menuName+"-测试文章数据正文<br/>测试文章数据正文<br/>测试文章数据正文<br/>测试文章数据正文<br/>测试文章数据正文<br/></p>");
							articleData.put("create_time",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) );
							this.getCommonService().getJdbcDao().addObj(DBTable.article, articleData);
						}
						
						
					}
					
					
					
				}
			}*/
			
			result.put("result",1);
			result.put("msg", "操作成功");
		}else {
			result.put("result",0);
			result.put("msg", "参数为空");
		}
		
		
		
		
		return WebUtil.resultString(result,request);
	}
	
	@RequestMapping(value="/delTestData",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String delTestData(@RequestBody Map data,HttpServletRequest request){
		Map result=new HashMap();
		List menuList=(List)data.get("menuList");
		if(menuList!=null && menuList.size()>0) {
			
			
			List menuDataList=this.getCommonService().getJdbcDao().querySql("select id,module,name,site_id from "+DBTable.menu+" where del_flag=0 and module in('news','links','article') and id in ("+org.apache.commons.lang3.StringUtils.join(menuList, ",")+")");
			
			if(menuDataList!=null) {
				for(int m=0;m<menuDataList.size();m++) {
					Map menu=(Map)menuDataList.get(m);
					String moduleName=menu.get("module").toString();
					String menuName=menu.get("name").toString();
					String menuId=menu.get("id").toString();
					String siteId=menu.get("site_id").toString();
					
					if(moduleName.equals("news")) {
						this.getCommonService().getJdbcDao().delete(DBTable.news, "where menu_id=? and name like '%测试资讯数据%'", new Object[] {menuId});
					}else if(moduleName.equals("links")) {
						this.getCommonService().getJdbcDao().delete(DBTable.links, "where menu_id=? and name like '%测试链接数据%'", new Object[] {menuId});
					}else if(moduleName.equals("article")) {
						Map articleData=this.getCommonService().getJdbcDao().queryRow("select id from "+DBTable.article+" where menu_id=? and content like '%测试文章数据正文%' and del_flag=0", new Object[] {menuId});
						if(articleData!=null) {
							this.getCommonService().getJdbcDao().delete(DBTable.article, "where id=?",new Object[] {articleData.get("id")});
						}
					}
				}
			}
			
			result.put("result",1);
			result.put("msg", "操作成功");
		}else {
			result.put("result",0);
			result.put("msg", "参数为空");
		}
		
		
		
		
		return WebUtil.resultString(result,request);
	}
	
}
